package models

import (
	"chatgpt/helper"
	"chatgpt/helper/code"
	mcache "github.com/patrickmn/go-cache"
	"github.com/slclub/go-tips"
	"time"
)

var cacheMemory *mcache.Cache

func init() {
	cacheMemory = mcache.New(time.Minute, 10*time.Minute)
}

func ConfModels(force bool) (code.CODENO, []map[string]any) {
	_tmp_fine_list := cacheModelList()
	if len(_tmp_fine_list) > 0 && force == false {
		return code.SUCCESS, _tmp_fine_list
	}
	dataa := helper.Config().Get("models")
	//dataa := cnf.Get("models")
	if dataa == nil {
		return code.SUCCESS, _tmp_fine_list
	}
	_tmp_fine_list = []map[string]any{}
	if arr, ok := dataa.([]any); ok {
		for _, val := range arr {
			if v, ok := val.(map[string]any); ok && tips.Int(v["hidden"]) == 0 {
				_tmp_fine_list = append(_tmp_fine_list, map[string]any{
					"BaseModel": v["basemodel"],
					"Model":     v["model"],
					"Desc":      v["desc"],
					"Avatar":    v["avatar"],
					"Company":   v["company"],
				})
			}
		}
		cacheModelListSet(_tmp_fine_list)
		return code.SUCCESS, _tmp_fine_list
	}
	return code.SUCCESS, _tmp_fine_list
}

func GetCompanyWithModel(smodel string) string {
	_, data_arr := ConfModels(false)
	for _, v := range data_arr {
		if v["Model"] == smodel {
			val, ok := v["Company"].(string)
			if ok {
				return val
			}
			return ""
		}
	}
	return ""
}

func cacheModelList() []map[string]any {
	v, ok := cacheMemory.Get("model-list")
	if !ok {
		return nil
	}
	rtn, ok := v.([]map[string]any)
	if !ok {
		return nil
	}
	return rtn
}

func cacheModelListSet(data []map[string]any) {
	cacheMemory.Set("model-list", data, 5*time.Minute)
}
